package com.example.demo2;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView editText;
    private Button button;
    private TextView textView5;
    int time;
    Handler handler = new Handler(){
        //处理消息，获取内容进行更新
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            textView5.setText("还剩：" + msg.arg1 + "秒");
            System.out.println("111");
            if (time == msg.arg1) {
                System.out.println("222");
                Toast.makeText(MainActivity.this,"计时结束",Toast.LENGTH_SHORT);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        editText = (TextView) findViewById(R.id.editText);
        button = (Button) findViewById(R.id.button);
        textView5 = (TextView) findViewById(R.id.textView5);
        button.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        time = Integer.valueOf(editText.getText().toString());
        switch (v.getId()) {
            case R.id.button:
                new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        for (int i = time; i >=0; i--) {
                            try {
                                Thread.sleep(1000);
                                Message message = handler.obtainMessage();
                                message.arg1=i;
                                handler.sendMessage(message);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }.start();
                break;
        }
    }
}